import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history } from 'umi';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { getUserinfoByToken } from '@/services/api';

const loginPath = '/user/login';

export const initialStateConfig = {
  loading: <PageLoading />,
};


export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  fetchUserInfo?: () => Promise<any>;
}> {
  const fetchUserInfo = async () => {

    try {
      const res = await getUserinfoByToken();
      return res;
    } 
    catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();

    return {
      fetchUserInfo,
      currentUser,
      settings: {},
    };
  }
  return {
    fetchUserInfo,
    settings: {},
  };
}

export const layout: RunTimeLayoutConfig = ({ initialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.data?.userinfo?.name,
      fontSize: 18,
      gapX: 150,
      gapY: 125,
      // fontColor: '#f1f1f1'
      zIndex: 99999,
    },
    footerRender: () => <Footer />,
    // onPageChange: () => {
    //   const { location } = history;
    //   if (initialState?.currentUser?.code !== 200 && location.pathname !== loginPath) {
    //     history.push(loginPath);
    //   }
    // },
    menuHeaderRender: undefined,
    unAccessible: <div>unAccessible</div>,
    ...initialState?.settings,
  };
};
